import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import router from 'umi/router';

import api from '@/api';
import { setAuthority, getAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import Des from '@/utils/des';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'auth',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload ,callback}, { call, put }) {
      console.log("payload",payload)
      console.log(api.auth.login)
      // if (payload.data.password) {
      //   payload.data.password = Des.enc(payload.data.password);
      // }
      const response = yield call(api.auth.login, payload);
      console.log("response",response)
      callback(response);
      // if (!response) return;
      // let role = response.data.userStore.master ? 'master' : 'user';
      setAuthority('master');
      // Login successfully
      if (response.errorCode === 0) {
        reloadAuthorized();
        // yield put.resolve({ type: 'menu/fetchMenu' });
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        console.log(redirect)
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *logout(_, { call, put }) {
      if (getAuthority() !== 'guest') {
        let res = yield call(api.auth.logout);
        if (res.errorCode === 0) {
          setAuthority('guest');
          yield put({ type: 'menu/clear' });
          router.push('/auth/login');
        }
      }
    },
    *SelectUserInfo({ payload , callback }, { call }) {
      const response = yield call(api.auth.SelectUserInfo, payload)
      console.log(response)
      callback(response);
    },
    *postCode({ payload , callback }, { call }) {
      const response = yield call(api.auth.postCode, payload)
      console.log(response)
      callback(response);
    },
    *register({ payload , callback }, { call }) {
      const response = yield call(api.auth.register, payload)
      console.log(response)
      callback(response);
    },
    
    *updatePassword({ payload }, { call }) {
      return yield call(api.auth.updatePassword, payload)
    },
    *forceUpdatePassword({ payload }, { call }) {
      return yield call(api.auth.forceUpdatePassword, payload)
    },

  },

  reducers: {
  },
};
